from django.shortcuts import render
from django.http import HttpResponse
import re






class AdminLoginMiddleware:
    def __init__(self,get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 中间件把首页登录验证码的请求给拦截了.在这里把ajax请的地址给允许
        # 后台 admin下有哪些是允许的:
        urllist = ['/admin/vcode','/admin/login','/admin/dologin','/admin/vcodeajax']
        # 排除这些以外的匹配任何admin后面的页面都进行session验证:
        if re.match('/admin',request.path) and request.path not in urllist:
            # 检测当前是否已经登录,如果没有登录了,说明session中没有session['adminuser'],如提示登录
            if request.session.get('adminuser',None) == None:
                return HttpResponse('<script>alert("请先登录");location.href="/admin/login"</script>')



        # 前台需要限制的路径
        urllist2 = ['/orderconfirm','/ordercaerte','/orderbuy','/myorder','/member']
        print(re.match('/member',request.path))
        if request.path in urllist2 or  re.match('/member',request.path):
            # 是否登录
            if not request.session.get('vipuser',None):
                return HttpResponse('<script>alert("请先登录");location.href="/login"</script>')

        response = self.get_response(request)
        return response


